import type { Context } from 'koa'
import type { IUserModel } from '../model/user'
import { User } from '../model'
import { SxoUserModel } from '../model/all'
import { Paging } from '../dto/base'
import { decodeToken } from '~/core/auth'

export const createOne = async (newOne: any): Promise<any> => {
    const one = await SxoUserModel.findOne({ where: { username: newOne.username } })
    if (one) {
        global.UnifyResponse.parameterException(10409)
    }
    return await SxoUserModel.create(newOne)
}

export const updateOne = async (newOne: any): Promise<any> => {
    const one = await SxoUserModel.findByPk(newOne.id)
    if (!one) {
        global.UnifyResponse.notFoundException(10404)
    }
    return await one!.update(newOne)
}

export const getById = async (id: number): Promise<any> => {
    debugger
    const one = await SxoUserModel.findByPk(id)
    if (!one) {
        global.UnifyResponse.notFoundException(10404)
    }
    return one!
}

export const getOneByUsername = async (username: string): Promise<any> => {
    const one = await SxoUserModel.findOne({ where: { username } })
    if (!one) {
        global.UnifyResponse.notFoundException(10404)
    }
    return one!
}

export const deleteById = async (id: number): Promise<boolean> => {
    const numDeleted = await SxoUserModel.destroy({ where: { id } })
    return !!numDeleted
}

export const getList = async (): Promise<any> => {
    return await SxoUserModel.findAll()
}

export const getPage = async (ctx: Context): Promise<Paging<any>> => {
    const { start, limit } = ctx.validatedQuery
    const offset = (start - 1) * limit
    const pageRel = await SxoUserModel.findAll({ offset, limit })
    const totalRel = (await SxoUserModel.findAll()).length

    return new Paging(pageRel, totalRel, start, limit)
}

export const curUser = async (ctx: Context): Promise<any> => {
    const bearerToken = ctx.header.authorization
    const token = bearerToken!.split(' ')[1]
    const userId = decodeToken(token!)
    const one = await getById(userId)
    return one
}
